package org.ft.zy;

import org.ft.zy.config.AliyunOSSConfig;
import org.ft.zy.config.DatabaseConfig;
import org.ft.zy.model.Article;
import org.ft.zy.util.AliyunOSSUtil;
import org.ft.zy.util.MysqlUtil;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 清理oss中未使用的图片
 * 发现博客中一图多用的图片key
 * add by zara@2023-8-30
 */
public class App {

    private static Map<String, String> context = new HashMap<>();
    private static String folder = "md";

    public static void main(String[] args) {
        try {
            initContext(args);
            clean();
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }

    }

    public static void initContext(String[] args) throws IllegalAccessException {
        for (String arg : args) {
            int index = arg.indexOf('=');

            String name = arg.substring(2,index).replaceAll("\\.", "_").toUpperCase();
            String value = arg.substring(index+1);
            context.put(name, value);
        }
        initContext(AliyunOSSConfig.class);
        initContext(DatabaseConfig.class);
        System.out.println("Context init successfully.");
    }

    private static <T> void initContext(Class<T> clazz) throws IllegalAccessException {
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if (!Modifier.isFinal(field.getModifiers()) && Modifier.isStatic(field.getModifiers())) {
                String value = context.get(field.getName());
                if (value != null) {
                    field.setAccessible(true);
                    field.set(null, value);
                }
            }
        }
    }


    public static void clean() {
        List<Article> rlist = MysqlUtil.list(Article.class);
        Map<String, Integer> fileMap = new HashMap<>();
        for (Article article : rlist) {
            List<String> list = findPicUrls(article.getContent2());
            for (String key : list) {
                fileMap.put(key, fileMap.getOrDefault(key, 0) + 1);
            }
        }

        List<String> cleanList = new ArrayList<>();
        List<String> ossList = AliyunOSSUtil.listAll(folder);
        for (String key : ossList) {
            if (!fileMap.containsKey(key)) {
                cleanList.add(key);
            }
        }


        List<String> dupList = new ArrayList<>();
        for (String key : fileMap.keySet()) {
            if (fileMap.get(key) > 1) {
                dupList.add(key);
            }
        }


        if (cleanList.size() > 0) {
            System.out.println("Exists pictures unused, show their keys below: ");
            System.out.println(cleanList);
            System.out.print("Do you want to clean the " + cleanList.size() + " pictures?[yes,no]");
            Scanner scanner = new Scanner(System.in);
            String response = scanner.nextLine();
            if (response.equals("yes")) {
                System.out.print("The clean action id danger, please confirm it.[yes,no]");
                response = scanner.nextLine();
                if (response.equals("yes")) {
                    AliyunOSSUtil.deleteFileList(cleanList);
                    System.out.println("Clean pictures successfully.");
                }
            }
        }
        System.out.println("Exists duplicate key references,following are the keys, look at the database for more information!!!");
        System.out.println(dupList);

    }

    public static List<String> findPicUrls(String content) {

        List<String> list = new ArrayList<>();
        String pattern = "(https://" + AliyunOSSConfig.BUCKE_NAME + '.' + AliyunOSSConfig.END_POINT + "/" + ")(\\S*?\")";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(content);
        while (m.find()) {
            String fileName = m.group(2);
            String key = fileName.substring(0, fileName.length() - 1);
            list.add(key);
        }
        return list;
    }
}
